//
//  TSCRegister.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-15.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCVCRegister.h"
#import "TSCConstants.h"
#import "TSCMyUIUtil.h"
#import "TSCMyUtil.h"
#import "TSCMyCheckUtil.h"
#import "TSCMyNetworkUtil.h"
#import "TSCMyHttpUtil.h"
#import "TSCMyClickBtn.h"

@interface TSCVCRegister () {
    // 方法一：手工声明属性，可以响应键盘收起事件
    //    UITextField * _tfEmail;
    //    UITextField * _tfUserName;
    //    UITextField * _tfPasswd;
}

// 方法二：通过拖拽生成属性，可以响应键盘收起事件
@property (weak, nonatomic) IBOutlet UITextField *tfEmail;
@property (weak, nonatomic) IBOutlet UITextField *tfUserName;
@property (weak, nonatomic) IBOutlet UITextField *tfPasswd;
@property (weak, nonatomic) IBOutlet UIButton *btnRegister;

@end

@implementation TSCVCRegister

+ (id) vcRegisterWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_REGISTER];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 注册事件——监听代理
    _tfEmail.delegate = self;
    _tfUserName.delegate = self;
    _tfPasswd.delegate = self;
    
    // 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:YES goBackVC:nil hasAppLogo:YES titleResourceKey:@"title_register" iconResourceNameArray:nil iconClickedListenerArray:nil];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (IBAction)register_pre:(id)sender {
    // 收起键盘
    [self resignAllFirstResponder];
    
    // 检查各参数
    NSString * email = [TSCMyUtil trim:_tfEmail.text];
    NSString * userName = [TSCMyUtil trim:_tfUserName.text];
    NSString * passwd = [TSCMyUtil trim:_tfPasswd.text];
    
    if([TSCMyCheckUtil checkWithString:email regexType:RegexTypeEmail] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_format_email"];
        return;
    }
    
    if([TSCMyCheckUtil checkWithString:userName regexType:RegexTypeUserName] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_format_username"];
        return;
    }
    
    if([TSCMyCheckUtil checkWithString:passwd regexType:RegexTypePasswd] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_format_passwd"];
        return;
    }
    
    // 先检查网络情况，若不可用，直接返回
    if([TSCMyNetworkUtil checkNetwork] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_network_unavailable"];
        return;
    }
    
    
    // 提示用户正在注册
    [self showDialogWithResourceKey:@"title_registering" isProcessing:YES];
    
    // 注册
    [self register_P1:email userName:userName passwd:passwd];
}

/* private */ - (void) register_P1:(NSString *)email userName:(NSString *)userName passwd:(NSString *)passwd {
    
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:email forKey:@"email"];
    [reqDic setObject:userName forKey:@"user_name"];
    [reqDic setObject:[TSCMyUtil getMD5:passwd] forKey:@"passwd"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_USER_REGISTER dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString, NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                return;
            }
            case ServerRespTypeErrCode:{
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithString:msg];
                return;
            }
            default:
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                return;
        }
        
        // 解析服务器返回
        NSInteger Id = [[contentDictionary objectForKey:@"id"]intValue];
        NSString * name = [contentDictionary objectForKey:@"name"];
        NSString * email = [contentDictionary objectForKey:@"email"];
        
        // 保存用户设置
        [_ud setInteger:Id forKey:UD_USER_ID];
        [_ud setObject:name forKey:UD_USER_NAME];
        [_ud setObject:email forKey:UD_USER_EMAIL];
        [_ud setObject:name forKey:UD_USER_NAME_OR_EMAIL];
        [_ud synchronize];
        
        
        // 提示用户已经申请成功
        TSCMyDialog * dialog = [[TSCMyDialog alloc]init];
        dialog.msgText = msg;
        [_dialog replaceContentViewWithOtherDialog:dialog];
        
        // 退回上一个vc（登陆界面）
        [TSCMyUtil executeBlockAfterTI:CONFIG_MY_DIALOG_CLOSE_S block:^{
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }];
}

/* private */ - (void) resignAllFirstResponder {
    [_tfEmail resignFirstResponder];
    [_tfUserName resignFirstResponder];
    [_tfPasswd resignFirstResponder];
}

/**
 * return键收回键盘
 *
 * @author Rio
 * @date 2015-05-21
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

/**
 * 点击空白区域收回键盘
 *
 * @author Rio
 * @date 2015-05-21
 */
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // 2015-05-26 Rio 经测试，完全可以
    [self resignAllFirstResponder];
}

@end
